const fs = require("fs")
const compressing = require("compressing")
const os = require("os")
const path = require("path")
const cmd = require("./lib/cmd")
const config = require("./lib/config")
const log = require("./lib/log.js")

const isDev = process.env.NODE_ENV !== 'production';
const appData = path.resolve(os.homedir(), config.getAppDataDir())

module.exports.run = async opt => {
  try {

    let forceLocal = opt.forceLocal || false
    let params = opt.params || []
    let vmparams = opt.vmparams || []


    let name = opt.name
    if (!name) {
      throw new Error("name-不能为空")
    }
    let jarPath = opt.jar
    if (!jarPath) {
      throw new Error("jar-不能为空")
    }
    if (!fs.existsSync(jarPath)) {
      throw new Error(`找不到文件：${jarPath}`)
    }

    // 判断本地环境是否正确
    let jrePath = path.resolve(appData, name, "jre")
    let javaComman = path.resolve(jrePath, "bin/java");
    if (process.platform === 'linux') {
      await cmd.cmdExec("chmod", ['+x', javaComman])
    }
    let versionInfo = await cmd.cmdExec(javaComman, ['-version'], true, true)
    log.info(versionInfo)
    let infos = versionInfo.split("\r\n")
    if (infos.length) {
      if (/(java|openjdk)\sversion\s"(.+)"/.test(infos[0])) {
        log.info(`本地已解压jdk环境正确，版本：${RegExp.$2}`)
      } else {
        log.info("本地已解压jdk环境异常，即将重新解压jdk包")
        javaComman = ""
      }
    }

    if (!javaComman) {
      // 解压本地环境
      try {
        let jdkZipPath = opt.jdkZip
        if (!jdkZipPath) {
          throw new Error("jdkZip-不能为空")
        }
        if (!fs.existsSync(jdkZipPath)) {
          throw new Error(`找不到文件：${jdkZipPath}`)
        }
        let startTime = Date.now()
        let jrePath = path.resolve(appData, name, "jre")
        await compressing.zip.uncompress(jdkZipPath, jrePath)
        javaComman = path.resolve(jrePath, "bin/java")
        log.info(`解压缩耗时：${Date.now() - startTime} ms`)

        if (process.platform === 'linux') {
          await cmd.cmdExec("chmod", ['+x', javaComman])
        }
        let versionInfo = await cmd.cmdExec(javaComman, ['-version'], true, true)
        log.info(versionInfo)
        let infos = versionInfo.split("\r\n")
        if (infos.length) {
          if (/(java|openjdk)\sversion\s"(.+)"/.test(infos[0])) {
            log.info(`新解压缩的jdk正确，版本：${RegExp.$2}`)
          } else {
            log.info("新解压缩jdk环境异常，即将使用系统jdk")
            throw new Error("新解压缩jdk环境异常")
          }
        }
      } catch (e) {
        if (forceLocal) throw e
        javaComman = ""
      }
    }
    // 不强制本地
    if (!forceLocal && !javaComman) {
      javaComman = "java"
      // 判断系统环境是否有java
      let versionInfo = await cmd.cmdExec(javaComman, ['-version'], true, true)
      log.info(versionInfo)
      let infos = versionInfo.split("\r\n")
      if (infos.length) {
        if (/(java|openjdk)\sversion\s"(.+)"/.test(infos[0])) {
          log.info(`系统环境jdk正确，版本：${RegExp.$2}`)
        } else {
          // 不存在系统jdk，使用配置的jdk
          log.info("系统jdk环境异常，启动失败")
          throw new Error("jdk配置不正确")
        }
      }
    }

    if (opt.debugPort) {
      vmparams.unshift(`-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=${opt.debugPort}`)
    }

    return cmd.cmdExec(javaComman, [
      ...vmparams,
      "-jar",
      jarPath,
      ...params
    ])
  } catch (e) {
    log.error(`运行runjava失败：${e}`)
    throw e
  }
}
